package k2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;

public class Spreadsheet {
	private Utils utils = new Utils();
	private ArrayList<Student> students = new ArrayList<Student>();
	private boolean found = false;
	private String inputLine = "";
	private Cache cache = new Cache();
	private String[] entryArray = null;
	public Spreadsheet(String id, int updateTime) throws IOException{
		printInfo(createStudents(getURLinfo()), id, updateTime);
	}
	/**
	 * Gets info from given URL and writes it to file
	 * @return
	 * @throws IOException
	 */
	private String getURLinfo() throws IOException{
		URL api = null;
		try {
			api = new URL("https://spreadsheets.google.com/feeds/list/0AnoMCh3_x82sdERLR3FvVDBIWXpjT1JlcENmOFdERVE/od7/public/basic");
			 BufferedReader in = new BufferedReader(
				        new InputStreamReader(api.openStream()));
			 inputLine = in.readLine();
			return inputLine;
		} catch (IOException e) {
			System.out.println("Interneti ühendus puudub, loen puhvrist");
			inputLine = cache.readFile();
			return inputLine;
		}
	}
	private void printInfo(ArrayList<Student> students, String userId, int updateTime) throws IOException{
		for(Student student : students){
			if(updateTime != 0 && (utils.currentDateInDays() - utils.dateToDays(student.getUpdate()) <= updateTime) && userId.equalsIgnoreCase("")){
				found = true;
				System.out.println(student.getTitle() + " - " + student.getContent()+ " - Last updated: "
						+ utils.properTime(student.getUpdate()));
			}else if((userId.equalsIgnoreCase("all") || userId.equalsIgnoreCase("")) && updateTime == 0){
				found = true;
				if(cache.checkForUpdate(student)){
					System.out.println("*** " + student.getTitle() + " - " + student.getContent()+ " - Last updated: "
							+ utils.properTime(student.getUpdate()));
				}else{
					System.out.println(student.getTitle() + " - " + student.getContent()+ " - Last updated: "
							+ utils.properTime(student.getUpdate()));
				}
			}else if((student.getTitle().contains(userId) || student.getUid().contains(userId)) && updateTime == 0){
				found = true;
				if(cache.checkForUpdate(student)){
					System.out.println("*** " + student.getTitle() + " <"+ student.getUid()+">"  + " - " + student.getContent()+ " - Last updated: "
							+ utils.properTime(student.getUpdate()));
				}else{
					System.out.println(student.getTitle() + " <"+ student.getUid()+">"  + " - " + student.getContent() + " - Last updated: "
							+ utils.properTime(student.getUpdate()));
				}
			}
		}
		if(found == false && updateTime == 0){
			System.out.println("Sellise koodiga üliõpilane puudub");
		}else if(found == false && updateTime != 0){
			System.out.println("Viimase "+updateTime+" päeva sees pole tehtud ühtegi muudatust");
		}
		try {
			if(inputLine == null){
				inputLine = "";
			}
			cache.writeFile(inputLine);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private ArrayList<Student> createStudents(String input){
		entryArray = utils.substringsBetween(input, "<entry>", "</entry>");
		String[] title = null;
		String[] uidBuffer = null;
		String[] uid = null;
		String[] update = null;
		String[] content = null;
		try{
			for(String entry : entryArray){
				title = utils.substringsBetween(entry, "<title type='text'>", "</title>");
				update = utils.substringsBetween(entry, "<updated>", "</updated>");
				uidBuffer = utils.substringsBetween(entry, "<id>", "</id>");
				uid = uidBuffer[0].split("/");
				content = utils.substringsBetween(entry, "<content type='text'>", "</content>");
				students.add(new Student(title[0], uid[9], update[0], content[0]));
			}
		}catch(NullPointerException e){
			System.out.println("Puhver puudub või on tühi");
			System.exit(0);
		}
		return students;
	}
}
